package Day012_多线程2.demo02_Lock锁;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangyan
 * @date 2020/4/30 10:44
 */
/*
    java.util.concurrent.locks.Lock 机制提供了比synchronized代码块和synchronized方法更广泛的锁定操作,
    同步代码块/同步方法具有的功能Lock都有,除此之外更强大.

    Lock锁也称同步锁，加锁与释放锁方法化了:
                public void lock() :加同步锁。
                public void unlock() :释放同步锁。

    Lock是接口,可以创建其实现类对象(ReentrantLock)来使用.
 */

public class Lock锁 {
    public static void main(String[] args) {
        //创建线程任务对象
        MyRunnable ticket = new MyRunnable();
        //创建三个窗口对象
        Thread t1 = new Thread(ticket, "窗口1");
        Thread t2 = new Thread(ticket, "窗口2");
        Thread t3 = new Thread(ticket, "窗口3");
        //同时卖票
        t1.start();
        t2.start();
        t3.start();
    }
}

class MyRunnable implements Runnable {
    int ticket = 100;
    //创建锁的实现类对象
    Lock lock = new ReentrantLock();

    public void run() {
        while (true) {
            //加锁
            lock.lock();
            if (ticket < 1) {
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //获取当前线程对象的名字
            String name = Thread.currentThread().getName();
            System.out.println(name + "正在卖第:" + ticket + "张票");
            ticket--;
            //释放锁
            lock.unlock();
        }
    }
}
